package com.kkd.kkdapp.activity;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Dialog;
import android.content.*;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.*;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.*;
import android.widget.CompoundButton.OnCheckedChangeListener;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.adapter.LiveDetailGridAdapter;
import com.kkd.kkdapp.adapter.LiveDetailGridAdapter.OnLiveHomeDataLiveClick;
import com.kkd.kkdapp.adapter.LiveLikerHeadAdapter;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.db.CurUserModel;
import com.kkd.kkdapp.http.entity.LiveDetailData;
import com.kkd.kkdapp.http.entity.LiveHomeDataLive;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.listener.OnSingleClickListener;
import com.kkd.kkdapp.utils.DialogUtils;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.KkdPlayerManager;
import com.kkd.kkdapp.utils.KkdPlayerManager.PlayerCallback;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.List;

public class LivePlayerActivity extends BaseActivity {

	public static final String TAG = "LivePlayerActivity";

	public static final int DETAIL_GOT_SUCCESS = 0;
	public static final int DETAIL_GOT_FAIL = 1;
	public static final int CMD_START = 2;
	public static final int VIDEO_STOPED_TIME_OUT = 3;
	public static final int INITSURFACE = 4;

	private static boolean isFirstPlayer = true;

	private LiveHomeDataLive mLiveHomeData;
	private LiveDetailData mLiveDetailData;
	private boolean isCanShare = true;
	private KkdPlayerManager mPlayer;
	private SurfaceHolder mSurfaceHolder = null;
	private SurfaceView mSurfaceView = null;
	private SeekBar mSeekBar = null;
	private FrameLayout frameContainer;
	private RelativeLayout back;
	private Button play_button;
	private Button pause_view;
	private RecyclerView head_list;
	private TextView video_title;
	private TextView looker_count_tv;
	private Button share_bt;
	private TextView video_title2;
	private TextView looker_count_tv2;
	private Button share_bt2;
	private TextView desc_first;
	private CheckBox show_more_bt;
	private TextView desc_more;
	private LinearLayout desc_line;
	private TextView total_duration;
	private LinearLayout like_line;
	private ImageView like_finger;
	private ImageView live_tips;
	private TextView like_tv;
	private TextView like_count_tv;
	private LiveDetailGridAdapter mGridAdapter;
	private List<LiveHomeDataLive> list_related = new ArrayList<LiveHomeDataLive>();
	private GridView related_grid;
	private LiveLikerHeadAdapter mLiveLikerHeadAdapter;
	private ArrayList<String> list_liker = new ArrayList<String>();
	private ImageView cover_img;
	private Button full_screen_bt;
	private Button small_screen_bt;
	private Button like_finger2;
	private TextView like_count_tip;
	private RelativeLayout title_rl;
	private RelativeLayout surface_rl;
	private RelativeLayout root_view;
	private LinearLayout full_screen_title_layout;
	private RelativeLayout full_screen_Layout;
	private LinearLayout progress_layout;
	private RelativeLayout buttonLayout;
	private TextView title_tv;
	private ImageView kkd_logo;
	private TextView err_tv;

	private float wPh = 8f / 15f;

	private boolean mEnableUpdateProgress = true;
	private String msURI;
	private GestureDetector mGestureDetector;
	private int mPosition = 0;
	private PowerManager.WakeLock mWakeLock = null;
	private boolean isLastWifiConnected = false;

	// 标记播放器是否已经暂停
	private boolean isPausePlayer = false;
	// 用来控制应用前后台切换的逻辑
	private boolean isCurrentRunningForeground = true;
	// 非静音图标
	private ImageView player_volume_icon;
	// 静音图标
	private ImageView video_player_mute_icon;
	// 音量父控件
	private RelativeLayout player_volume_ll;
	// 音量进度条
	private RatingBar ratingBar;
	private Dialog loadDialog;

	// 重点:发生从wifi切换到4g时,提示用户是否需要继续播放,此处有两种做法:
	// 1.从历史位置从新播放
	// 2.暂停播放,因为存在网络切换,续播有时会不成功
	private BroadcastReceiver connectionReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			ConnectivityManager connectMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
			NetworkInfo mobNetInfo = connectMgr
					.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
			NetworkInfo wifiNetInfo = connectMgr
					.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

			if (!isLastWifiConnected && wifiNetInfo.isConnected()) {
				isLastWifiConnected = true;
			}
			if (isLastWifiConnected && mobNetInfo.isConnected()
					&& !wifiNetInfo.isConnected()) {
				isLastWifiConnected = false;
				if (mPlayer != null) {
					// 重点:新增接口,此处必须要将之前的surface释放掉
					pausePlayer();
				}
				tell4G2UseDialog();
			}
		}
	};

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case INITSURFACE:
				initSurface();
				break;
			case VIDEO_STOPED_TIME_OUT:
				if (mPlayer != null) {
					if (isPausePlayer) {
						mPlayer.replay();
					} else {
						mPlayer.reset();
						mPlayer.playUrl(msURI);
						if(mPosition!=0)
							mPlayer.seekTo(mPosition);
						update_progress(mPosition);
					}
					show_pause_ui(true, false);
					mHandler.removeCallbacks(mUpdateProgressRunnable);
					mHandler.postDelayed(mUpdateProgressRunnable, 1000);
				} else {
					mHandler.sendEmptyMessage(INITSURFACE);
				}

				break;
			case DETAIL_GOT_FAIL:
				break;
			case DETAIL_GOT_SUCCESS:
				if (mLiveDetailData.isLiked()) {
					like_tv.setText("已赞");
					like_line
							.setBackgroundResource(R.drawable.bg_like_round_gray);
					like_finger2.setEnabled(false);
				} else {
					like_tv.setText("点赞");
					like_finger2.setEnabled(true);
					like_line
							.setBackgroundResource(R.drawable.bg_like_round_red);
				}

				looker_count_tv2.setText("共"
						+ (mLiveDetailData.getVideo().getPlayCount()) + "人观看");
				looker_count_tv.setText("共"
						+ (mLiveDetailData.getVideo().getPlayCount()) + "人观看");
				like_count_tv.setText(mLiveDetailData.getVideo().getLikeCount()
						+ "人赞过");
				list_related.clear();
				if (mLiveDetailData.getRelatedVideos() != null
						&& mLiveDetailData.getRelatedVideos().size() > 0) {
					findViewById(R.id.hai_line).setVisibility(View.VISIBLE);
					findViewById(R.id.no_more_tv).setVisibility(View.GONE);
					related_grid.setVisibility(View.VISIBLE);
					list_related.addAll(mLiveDetailData.getRelatedVideos());
					related_grid
							.setLayoutParams(new android.widget.LinearLayout.LayoutParams(
									android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
									SystemUtils
											.dip2px(LivePlayerActivity.this,
													(float) (180 * Math.ceil((list_related
															.size() / 2.0f)) + 15))));
					mGridAdapter.notifyDataSetChanged();
				} else {
					findViewById(R.id.no_more_tv).setVisibility(View.VISIBLE);
					findViewById(R.id.hai_line).setVisibility(View.GONE);
					related_grid.setVisibility(View.GONE);
				}

				list_liker.clear();
				if (mLiveDetailData.getVideo().getLikerAvatars() != null
						&& mLiveDetailData.getVideo().getLikerAvatars().size() > 0) {
					list_liker.addAll(mLiveDetailData.getVideo()
							.getLikerAvatars());
					// fliperListLiker();
					mLiveLikerHeadAdapter.notifyDataSetChanged();
					head_list.setVisibility(View.VISIBLE);
					like_count_tip.setVisibility(View.GONE);

				} else {
					head_list.setVisibility(View.GONE);
					like_count_tip.setVisibility(View.VISIBLE);
				}

				break;
			case CMD_START:
				// startToPlay();
				if (mPlayer != null && mPlayer.isPlaying() == false) {
					mPlayer.playUrl(msURI);
					show_pause_ui(true, false);
				}
				break;
			default:
				break;
			}
		}
	};

	private Dialog mDialog;

	protected void tell4G2UseDialog() {
		if (mDialog != null) {
			mDialog.cancel();
			mDialog = null;
		}
		mDialog = DialogUtils.generate2BDialog(this, "当前为移动网络，确认继续播放吗？", "退出",
				"确认", new OnClickListener() {

					@Override
					public void onClick(View v) {
						mDialog.dismiss();
						finish();
					}
				}, new OnClickListener() {

					@Override
					public void onClick(View v) {
						mDialog.dismiss();
						mHandler.sendEmptyMessage(VIDEO_STOPED_TIME_OUT);
					}
				});
		mDialog.show();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		registerReceiver(connectionReceiver, intentFilter);
		initData();
		setContentView(R.layout.activity_live_player);
		acquireWakeLock();
		initUI();

	}

	@Override
	protected void onResume() {
		System.out.println("LivePlayerActivity.onResume()");
		super.onResume();
		updateUI();
		if (live_tips.getVisibility() == View.GONE) {
			if (SystemUtils.getNetTypeName().equals("WIFI")) {
				showLoadDialog();
			} else if (SystemUtils.getNetTypeName().equals("无网络")) {
				report_error("无网络");
			} else {
				tell4G2UseDialog();
			}
		}
		getLiveDetail();// 拉取视频详情
	}

	@Override
	protected void onPause() {
		System.out.println("LivePlayerActivity.onPause()");
		super.onPause();
		if (mPlayer != null) {
			mHandler.removeCallbacks(mUpdateProgressRunnable);
			mHandler.removeCallbacks(mShowProgressRunnable);
		}
		pausePlayer();
	}

	@Override
	protected void onDestroy() {
		System.out.println("LivePlayerActivity.onDestroy()");
		releaseWakeLock();
		if (connectionReceiver != null) {
			unregisterReceiver(connectionReceiver);
		}
		if (mPlayer != null) {
			mPlayer.stop();
			mPlayer = null;
		}
		if (loadDialog != null) {
			loadDialog.cancel();
			loadDialog = null;
		}
		super.onDestroy();
	}

	@Override
	protected void onStart() {
		System.out.println("LivePlayerActivity.onStart()");
		super.onStart();
		if (!isCurrentRunningForeground) {
			Log.d(TAG, ">>>>>>>>>>>>>>>>>>>切到前台 activity process");
		}
	}

	@Override
	protected void onStop() {
		System.out.println("LivePlayerActivity.onStop()");
		super.onStop();
		isCurrentRunningForeground = isRunningForeground();
		if (!isCurrentRunningForeground) {
			Log.d(TAG, ">>>>>>>>>>>>>>>>>>>切到后台 activity process");
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			} else {
				finish();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private class MyGestureListener extends SimpleOnGestureListener {

		@Override
		public boolean onScroll(MotionEvent e1, MotionEvent e2,
				float distanceX, float distanceY) {

			final double FLING_MIN_DISTANCE = 0.5;
			final double FLING_MIN_VELOCITY = 0.5;

			if (e1.getY() - e2.getY() > FLING_MIN_DISTANCE
					&& Math.abs(distanceY) > FLING_MIN_VELOCITY) {
				onVolumeSlide(1);
			}
			if (e1.getY() - e2.getY() < FLING_MIN_DISTANCE
					&& Math.abs(distanceY) > FLING_MIN_VELOCITY) {
				onVolumeSlide(-1);
			}
			return super.onScroll(e1, e2, distanceX, distanceY);
		}
	}

	/*************************
	 * 
	 * 调节音量
	 * *********************/
	private int mVolumn = 50;

	private void onVolumeSlide(int vol) {

		if (mPlayer != null) {
			mVolumn += vol;
			if (mVolumn > 100)
				mVolumn = 100;
			if (mVolumn < 0)
				mVolumn = 0;
			if (mVolumn == 0) {
				player_volume_ll.setVisibility(View.VISIBLE);
				video_player_mute_icon.setVisibility(View.VISIBLE);
				player_volume_icon.setVisibility(View.GONE);
			} else {
				player_volume_ll.setVisibility(View.VISIBLE);
				player_volume_icon.setVisibility(View.VISIBLE);
				video_player_mute_icon.setVisibility(View.GONE);
			}
			int volumn = (int) (16 * (mVolumn * 0.01));
			ratingBar.setRating(volumn);
			mPlayer.setVolume(((float) mVolumn) / 100);
		}
	}

	@SuppressWarnings("deprecation")
	private void acquireWakeLock() {
		if (mWakeLock == null) {
			PowerManager pMgr = (PowerManager) this
					.getSystemService(Context.POWER_SERVICE);
			mWakeLock = pMgr.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK,
					"SmsSyncService.sync() wakelock.");

		}
		mWakeLock.acquire();
	}

	private void releaseWakeLock() {
		mWakeLock.release();
		mWakeLock = null;
	}

	private void update_progress(int ms) {
		if (mEnableUpdateProgress) {
			mSeekBar.setProgress(ms);
		}
	}

	private boolean isShowProgress = true;

	private void show_progress_ui(boolean bShowPause) {
		if (bShowPause) {
			mHandler.removeCallbacks(mShowProgressRunnable);
			isShowProgress = true;
			progress_layout.setVisibility(View.VISIBLE);
			if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
				full_screen_title_layout.setVisibility(View.VISIBLE);
				kkd_logo.setAlpha(0.3f);
			} else {
				kkd_logo.setAlpha(1f);
			}

		} else {
			mHandler.postDelayed(mShowProgressRunnable, 3000);
		}
	}

	Runnable mShowProgressRunnable = new Runnable() {
		@Override
		public void run() {
			isShowProgress = false;
			progress_layout.setVisibility(View.GONE);
			if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
				full_screen_title_layout.setVisibility(View.GONE);
			}
			kkd_logo.setAlpha(1f);
		}
	};
	Runnable mUpdateProgressRunnable = new Runnable() {
		@SuppressLint("DefaultLocale")
		@Override
		public void run() {

			if (mPlayer != null && mPlayer.isPlaying()) {

				if (mLiveHomeData.getVideoType() == 10) {
					update_progress(mPlayer.getCurrentPosition());
					mCurMs += 1;
					int min = mCurMs / 60;
					int sec = mCurMs % 60;
					String strCur = String.format("%02d:%02d", min, sec);
					total_duration.setText(strCur);
				} else {
					update_progress(mPlayer.getCurrentPosition());
				}

			}

			mHandler.postDelayed(this, 1000);
		}
	};

	private void show_pause_ui(boolean bShowPauseBtn, boolean bShowReplayBtn) {

		if (mLiveHomeData.getVideoType() == 10) {
			pause_view.setVisibility(View.GONE);
		} else {
			pause_view.setVisibility(bShowPauseBtn ? View.VISIBLE : View.GONE);
		}

		play_button.setVisibility(bShowReplayBtn ? View.VISIBLE : View.GONE);

	}

	/***********************
	 * 
	 * 初始化总时间
	 * 
	 * ********************/
	private int mCurMs = 0;
	private int mTotalDuration = 0;

	private void init_total_duration(int ms) {
		mCurMs = 0;
		mTotalDuration = (int) (ms / 1000.0f);

		mSeekBar.setMax(ms);
		mSeekBar.setKeyProgressIncrement(10000); // 5000ms = 5sec.
		mSeekBar.setProgress(0);
		mSeekBar.setSecondaryProgress(0); // reset progress now.

		mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

			@SuppressLint("DefaultLocale")
			public void onProgressChanged(SeekBar seekBar, int i,
					boolean fromuser) {
				int var = (int) (i / 1000.0f);
				int min2 = var / 60;
				int sec2 = var % 60;
				int min = mTotalDuration / 60;
				int sec = mTotalDuration % 60;
				String strCur = String.format("%02d:%02d", min2, sec2);
				String strTotal = String.format("%02d:%02d", min, sec);
				total_duration.setText(strCur + "/" + strTotal);
			}

			public void onStartTrackingTouch(SeekBar seekBar) {
				mEnableUpdateProgress = false;
			}

			public void onStopTrackingTouch(SeekBar seekBar) {
				int ms = seekBar.getProgress();
				mPlayer.seekTo(ms);
			}
		});

		return;
	}

	/********************
	 * 
	 * 播放异常处理
	 * ******************/
	private boolean isHasError = false;
	private void report_error(String err) {
		isHasError = true;
		pausePlayer();
		mSeekBar.setProgress(0);
		show_pause_ui(false, true);
		show_progress_ui(true);
		cover_img.setVisibility(View.VISIBLE);
		err_tv.setVisibility(View.VISIBLE);
		err_tv.setText(err);
		return;
	}
	
	private void report_compelte(String str) {
		if (mPlayer != null) {
			mPlayer.pause();
		}
		mPosition = 0;
		mSeekBar.setProgress(0);
		show_pause_ui(false, true);
		show_progress_ui(true);
		cover_img.setVisibility(View.VISIBLE);
		err_tv.setVisibility(View.VISIBLE);
		err_tv.setText(str);
		return;
	}

	private SurfaceHolder.Callback mSurfaceHolderCB = new SurfaceHolder.Callback() {
		@SuppressWarnings("deprecation")
		public void surfaceCreated(SurfaceHolder holder) {
			holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
			holder.setKeepScreenOn(true);
			mHandler.sendEmptyMessage(CMD_START);
		}

		public void surfaceChanged(SurfaceHolder holder, int format, int w,
				int h) {
		}

		public void surfaceDestroyed(SurfaceHolder holder) {
		}
	};

	/**
	 * 重点:初始化播放器使用的SurfaceView,此处的SurfaceView采用动态添加
	 * 
	 * @return 是否成功
	 */
	private boolean initSurface() {
		
//		if (mSurfaceView != null) {
//			mSurfaceView.setVisibility(View.GONE);
//			mSurfaceHolder.removeCallback(mSurfaceHolderCB);
//			mSurfaceHolder = null;
//		}
//		mSurfaceView = new SurfaceView(this);
		mSurfaceView = (SurfaceView) findViewById(R.id.surfaceView1);
		mSurfaceView.setVisibility(View.VISIBLE);
		if (mGestureDetector == null)
			mGestureDetector = new GestureDetector(this,
					new MyGestureListener());

		mSurfaceView.setZOrderOnTop(false);
		mSurfaceView.setOnTouchListener(new View.OnTouchListener() {
			@SuppressLint("ClickableViewAccessibility")
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (mGestureDetector.onTouchEvent(event))// 先响应调节音量
					return true;
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					return true;
				}
				if (event.getAction() == MotionEvent.ACTION_UP) {
					player_volume_ll.setVisibility(View.GONE);
					player_volume_icon.setVisibility(View.GONE);
					video_player_mute_icon.setVisibility(View.GONE);
					show_progress_ui(!isShowProgress);
				}
				return false;
			}
		});

		mPlayer = new KkdPlayerManager(mSurfaceView, mSeekBar,
				new PlayerCallback() {

					@Override
					public void onPrepared(MediaPlayer arg0) {
						cover_img.setVisibility(View.GONE);
						isHasError = false;
						if (loadDialog != null) {
							loadDialog.cancel();
							loadDialog = null;
						}
						if (mLiveHomeData.getVideoType() == 10) {
							mSeekBar.setEnabled(false);
						}else{
							mSeekBar.setEnabled(true);
						}
						if (mPlayer != null) {
							init_total_duration(mPlayer.getDuration());
							mHandler.removeCallbacks(mUpdateProgressRunnable);
							mHandler.postDelayed(mUpdateProgressRunnable, 1000);
							show_pause_ui(true, false);
							show_progress_ui(false);
						}
					}

					@Override
					public void onCompletion(MediaPlayer arg0) {
						if(!isHasError){
							if (mLiveHomeData.getVideoType() == 10) {
								report_compelte("直播已结束");
							} else {
								report_compelte("视频已播放完成");
							}
						}
						
					}

					@Override
					public void onVideoSizeChanged(MediaPlayer mp, int width,
							int height) {

					}

					@Override
					public boolean onInfo(MediaPlayer mp, int what, int extra) {
						switch (what) {
						case MediaPlayer.MEDIA_INFO_UNKNOWN:
							break;
						case MediaPlayer.MEDIA_INFO_BUFFERING_START:
							break;
						case MediaPlayer.MEDIA_INFO_BUFFERING_END:
							break;
						case MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING:
							break;
						case MediaPlayer.MEDIA_ERROR_TIMED_OUT:
							report_error("网络不好!");
							break;
						case MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
							break;
						}
						return false;
					}

					@Override
					public void onSeekComplete(MediaPlayer mp) {

						mEnableUpdateProgress = true;
					}

					@Override
					public boolean onError(MediaPlayer mp, int what, int extra) {
						if (loadDialog != null) {
							loadDialog.cancel();
							loadDialog = null;
						}
						switch (what) {
						case MediaPlayer.MEDIA_ERROR_TIMED_OUT:
							report_error("视频信号暂时中断,请稍后");
							break;
						case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
							report_error("视频信号暂时中断,请稍后");
							break;
						case MediaPlayer.MEDIA_ERROR_UNKNOWN:
							switch (extra) {
							case -1:
							case MediaPlayer.MEDIA_ERROR_IO:
								report_error("视频信号暂时中断,请稍后");
								break;
							default:
								break;
							}

							break;
						default:
							break;
						}
						System.out.println("what = " + what + "extra = "
								+ extra);
						return false;
					}

					@Override
					public void onBufferingUpdate(MediaPlayer arg0,
							int bufferingProgress) {
//						if (mEnableUpdateProgress) {
//							mSeekBar.setSecondaryProgress(mTotalDuration*bufferingProgress*10);  
//						}
					}
				});

		mSurfaceHolder = mSurfaceView.getHolder();
		mSurfaceHolder.addCallback(mSurfaceHolderCB);
		return true;
	}

	private void showLoadDialog() {
		if (loadDialog != null) {
			loadDialog.cancel();
			loadDialog = null;
		}
		loadDialog = DialogUtils
				.toLoadDialog(LivePlayerActivity.this, "加载中...");
		mHandler.sendEmptyMessageDelayed(VIDEO_STOPED_TIME_OUT, 1500);
	}

	private OnSingleClickListener mOnClick = new OnSingleClickListener(200) {

		@Override
		public void onSingleClick(View v) {
			switch (v.getId()) {
			case R.id.back:
				finish();
				break;
			case R.id.play_button:
				cover_img.setVisibility(View.GONE);
				mHandler.sendEmptyMessage(VIDEO_STOPED_TIME_OUT);
				break;
			case R.id.pause_button:
//				isPausePlayer = true;
//				mPlayer.pause();
//				show_pause_ui(false, true);
				pausePlayer();
				break;
			case R.id.share_bt2:
			case R.id.share_bt:
				if (isCanShare) {
					PreferenceUtils.getInstance().setH5Entrance(
							LivePlayerActivity.this, "视频分享");
					String shareUrl = com.kkd.kkdapp.Environment.getH5Url()
							+ "livedetail.html?vid=" + mLiveHomeData.getVid()
							+ "&avatarCnt=6";
					toShareURL(LivePlayerActivity.this, shareUrl, "我正在快快贷直播间看“"
							+ mLiveHomeData.getVideoName() + "”,一起来吧~", "",
							mLiveHomeData.getCoverUrl());
				} else {
					showToast("该视频不支持分享");
				}

				break;
			case R.id.like_finger2:
			case R.id.like_line:
				if (CurUserModel.getCurUser() != null) {
					if (like_tv.getText().toString().equals("点赞")) {
						like_finger2.setEnabled(false);
						like_tv.setText("已赞");
						Animation animation = AnimationUtils.loadAnimation(
								LivePlayerActivity.this, R.anim.like_anim);
						like_finger.startAnimation(animation);
						like_line
								.setBackgroundResource(R.drawable.bg_like_round_gray);
						doLike();
						String url = PreferenceUtils.getInstance().getHeadUrl(
								LivePlayerActivity.this);
						list_liker.add(0, url);
						mLiveLikerHeadAdapter.notifyDataSetChanged();
						like_count_tv
								.setText((mLiveHomeData.getLikeCount() + 1)
										+ "人赞过");
						head_list.setVisibility(View.VISIBLE);
						like_count_tip.setVisibility(View.GONE);
					} else {
						// 现有逻辑不允许取消点赞
						// like_tv.setText("点赞");
						// like_line
						// .setBackgroundResource(R.drawable.bg_like_round_gray);
						// undoLike();
					}
				} else {
					Intent intent = new Intent(LivePlayerActivity.this,
							LoginActivity.class);
					startActivity(intent);
				}

				break;
			case R.id.small_screen_bt:
			case R.id.full_screen_bt:
				if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
					setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
				} else {
					setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
				}
				break;
			case R.id.cover_img:
				if (live_tips.getVisibility() == View.VISIBLE) {
					int time = PreferenceUtils.getInstance().getLiveEnterTime(
							LivePlayerActivity.this);

					if (time < 2) {
						live_tips.setVisibility(View.GONE);
						ImageLoader.getInstance().displayImage(
								mLiveHomeData.getCoverUrl(), cover_img);
						show_progress_ui(true);
						PreferenceUtils.getInstance().setLiveEnterTime(
								LivePlayerActivity.this, time + 1);
					}
					mHandler.sendEmptyMessage(INITSURFACE);
				}
				show_progress_ui(!isShowProgress);

				break;
			case R.id.err_tv:
				err_tv.setVisibility(View.GONE);
				break;
			default:
				break;
			}

		}
	};

	private void initData() {
		// mLiveHomeData = mLiveHomeDataList.get(mLiveHomeDataList.size() - 1);
		mLiveHomeData = (LiveHomeDataLive) getIntent().getExtras()
				.getSerializable("LiveHomeDataLive");
		isPausePlayer = false;
		if (mLiveHomeData.getVideoType() == 10) {
			msURI = mLiveHomeData.getHlsUrl();
		} else {
			msURI = mLiveHomeData.getVodUrl();
		}
		msURI = msURI.replaceAll(" ", "%20");
		isCanShare = mLiveHomeData.getShareAuth() == 10;
	}

	private void initUI() {

		mSeekBar = (SeekBar) findViewById(R.id.progress);
		mSeekBar.setEnabled(false);
		like_count_tip = (TextView) findViewById(R.id.like_count_tip);
		progress_layout = (LinearLayout) findViewById(R.id.progress_layout);
		full_screen_Layout = (RelativeLayout) findViewById(R.id.full_screen_Layout);
		err_tv = (TextView) findViewById(R.id.err_tv);
		err_tv.setOnClickListener(mOnClick);
		buttonLayout = (RelativeLayout) findViewById(R.id.buttonLayout);
		kkd_logo = (ImageView) findViewById(R.id.kkd_logo);
		frameContainer = (FrameLayout) findViewById(R.id.GLViewContainer);

		back = (RelativeLayout) findViewById(R.id.back);
		back.setOnClickListener(mOnClick);
		play_button = (Button) findViewById(R.id.play_button);
		play_button.setOnClickListener(mOnClick);
		pause_view = (Button) findViewById(R.id.pause_button);
		pause_view.setOnClickListener(mOnClick);
		head_list = (RecyclerView) findViewById(R.id.head_list);
		head_list.setLayoutManager(new StaggeredGridLayoutManager(1,
				StaggeredGridLayoutManager.HORIZONTAL));
		mLiveLikerHeadAdapter = new LiveLikerHeadAdapter(this, list_liker,
				mLiveHomeData.getLikeCount());
		head_list.setAdapter(mLiveLikerHeadAdapter);
		head_list.setItemAnimator(new DefaultItemAnimator());
		title_rl = (RelativeLayout) findViewById(R.id.title_rl);
		video_title = (TextView) findViewById(R.id.video_title);
		video_title2 = (TextView) findViewById(R.id.video_title2);
		title_tv = (TextView) findViewById(R.id.title_tv);
		looker_count_tv = (TextView) findViewById(R.id.looker_count_tv);
		looker_count_tv2 = (TextView) findViewById(R.id.looker_count_tv2);
		share_bt = (Button) findViewById(R.id.share_bt);
		share_bt.setOnClickListener(mOnClick);
		share_bt2 = (Button) findViewById(R.id.share_bt2);
		share_bt2.setOnClickListener(mOnClick);
		desc_line = (LinearLayout) findViewById(R.id.desc_line);

		desc_first = (TextView) findViewById(R.id.desc_first);
		show_more_bt = (CheckBox) findViewById(R.id.show_more_bt);
		show_more_bt.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (isChecked) {
					desc_more.setVisibility(View.VISIBLE);
				} else {
					desc_more.setVisibility(View.GONE);
				}

			}
		});
		desc_more = (TextView) findViewById(R.id.desc_more);
		total_duration = (TextView) findViewById(R.id.total_duration);

		like_line = (LinearLayout) findViewById(R.id.like_line);
		like_line.setOnClickListener(mOnClick);
		like_finger = (ImageView) findViewById(R.id.like_finger);
		like_tv = (TextView) findViewById(R.id.like_tv);
		like_count_tv = (TextView) findViewById(R.id.like_count_tv);
		related_grid = (GridView) findViewById(R.id.related_grid);
		mGridAdapter = new LiveDetailGridAdapter(this, list_related,
				new OnLiveHomeDataLiveClick() {

					@Override
					public void OnLiveHomeDataLiveClick(LiveHomeDataLive ld) {
						Intent intent = new Intent(LivePlayerActivity.this,
								LivePlayerActivity.class);
						intent.putExtra("LiveHomeDataLive", ld);
						startActivity(intent);
						// ImageLoader.getInstance().stop();
						// // 重点:播放器没有停止,也没有暂停的时候,在activity的pause的时候也需要pause
						// if (mPlayer != null) {
						// mSeekBar.setProgress(0);
						// mHandler.removeCallbacks(mRunnable);
						// mHandler.removeCallbacks(mUIRunnable);
						// try {
						// mLiveHomeDataList.get(
						// mLiveHomeDataList.size() - 1)
						// .setmPosition(
						// mPlayer.getCurrentPosition());
						// } catch (Exception e) {
						// // TODO: handle exception 忽略
						// }
						// isHadNew = true;
						// stop();
						// }
						// mLiveHomeDataList.add(ld);
						// initData();
						// updateUI();
						// showDialog();
						// getLiveDetail();
					}
				});
		related_grid.setAdapter(mGridAdapter);
		related_grid.setFocusable(false);
		cover_img = (ImageView) findViewById(R.id.cover_img);
		cover_img.setOnClickListener(mOnClick);
		full_screen_bt = (Button) findViewById(R.id.full_screen_bt);
		full_screen_bt.setOnClickListener(mOnClick);
		small_screen_bt = (Button) findViewById(R.id.small_screen_bt);
		small_screen_bt.setOnClickListener(mOnClick);
		like_finger2 = (Button) findViewById(R.id.like_finger2);
		like_finger2.setOnClickListener(mOnClick);
		surface_rl = (RelativeLayout) findViewById(R.id.surface_rl);
		root_view = (RelativeLayout) findViewById(R.id.root_view);
		live_tips = (ImageView) findViewById(R.id.live_tips);

		full_screen_title_layout = (LinearLayout) findViewById(R.id.full_screen_title_layout);
		player_volume_icon = (ImageView) this
				.findViewById(R.id.player_volume_icon);
		video_player_mute_icon = (ImageView) this
				.findViewById(R.id.video_player_mute_icon);
		player_volume_ll = (RelativeLayout) findViewById(R.id.player_volume_ll);

		ratingBar = (RatingBar) this.findViewById(R.id.ratingBar);
		if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
			LayoutParams paramsFC = frameContainer.getLayoutParams();
			paramsFC.width = SystemUtils.getScreenWidth(this);
			paramsFC.height = (int) (paramsFC.width * wPh);
			frameContainer.setLayoutParams(paramsFC);

			LayoutParams paramsSl = surface_rl.getLayoutParams();
			paramsSl.width = SystemUtils.getScreenWidth(this);
			paramsSl.height = (int) (paramsFC.width * wPh);
			surface_rl.setLayoutParams(paramsSl);
		} else {
			android.widget.RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) surface_rl
					.getLayoutParams();
			params.width = SystemUtils.getScreenRealWidth(this);
			params.height = SystemUtils.getScreenRealHeight(this);
			surface_rl.setLayoutParams(params);

			android.widget.RelativeLayout.LayoutParams params3 = (android.widget.RelativeLayout.LayoutParams) frameContainer
					.getLayoutParams();
			params3.width = SystemUtils.getScreenRealWidth(this);
			params3.height = SystemUtils.getScreenRealHeight(this);
			frameContainer.setLayoutParams(params3);
		}
	}

	private void updateUI() {
		err_tv.setVisibility(View.GONE);
		title_tv.setText(mLiveHomeData.getVideoName());
		video_title2.setText(mLiveHomeData.getVideoName());
		video_title.setText(mLiveHomeData.getProgramName()
				+ mLiveHomeData.getVideoCode());
		looker_count_tv.setText("共" + (mLiveHomeData.getPlayCount()) + "人观看");
		looker_count_tv2.setText("共" + (mLiveHomeData.getPlayCount()) + "人观看");
		if (TextUtils.isEmpty(mLiveHomeData.getVideoDesc())) {
			desc_line.setVisibility(View.GONE);
		}
		desc_more.setText(mLiveHomeData.getVideoDesc());
		desc_first.setText(mLiveHomeData.getVideoName());
		if (mLiveHomeData.getVideoType() == 10) {
			total_duration.setText("00:00");
		} else {
			total_duration.setText("00:00/00:00");
		}
		like_count_tv.setText(mLiveHomeData.getLikeCount() + "人赞过");
		int time = PreferenceUtils.getInstance().getLiveEnterTime(this);
		if (isFirstPlayer && time < 2) {
			isFirstPlayer = false;
			live_tips.setVisibility(View.VISIBLE);
			progress_layout.setVisibility(View.GONE);
		} else {
			live_tips.setVisibility(View.GONE);
			cover_img.setVisibility(View.VISIBLE);
			cover_img.setImageResource(R.drawable.live_loading);
			ImageLoader.getInstance().displayImage(mLiveHomeData.getCoverUrl(),
					cover_img);
			show_progress_ui(true);

		}
	}

	private void pausePlayer() {
		if (mPlayer != null) {
			mPosition = mPlayer.getCurrentPosition();
			if(mPlayer.isPlaying())
				isPausePlayer = true;
			mPlayer.pause();
			show_pause_ui(false, true);
		}
	}

	// 重点:判定是否在前台工作
	public boolean isRunningForeground() {
		ActivityManager activityManager = (ActivityManager) this
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningAppProcessInfo> appProcessInfos = activityManager
				.getRunningAppProcesses();
		// 枚举进程
		for (ActivityManager.RunningAppProcessInfo appProcessInfo : appProcessInfos) {
			if (appProcessInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
				if (appProcessInfo.processName
						.equals(this.getApplicationInfo().processName)) {
					return true;
				}
			}
		}
		return false;
	}

	private void doLike() {
		KkdHttpMagager.getInstance().doLike(mLiveHomeData.getVid(),
				String.class, new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						// showToast(responseBody.toString());
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						showToast(desc);
					}
				});
	}

	private void getLiveDetail() {
		KkdHttpMagager.getInstance().getLiveDetail(1, 6,
				mLiveHomeData.getVid(), 8, LiveDetailData.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						mLiveDetailData = (LiveDetailData) responseBody;
						isCanShare = mLiveDetailData.getVideo().getShareAuth() == 10;
						mHandler.sendEmptyMessage(DETAIL_GOT_SUCCESS);
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						mHandler.sendEmptyMessage(DETAIL_GOT_FAIL);
					}
				});
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		System.out.println("LivePlayerActivity.onConfigurationChanged()");

		if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
			title_rl.setVisibility(View.VISIBLE);

			findViewById(R.id.live_title).setVisibility(View.VISIBLE);
			findViewById(R.id.like_frame).setVisibility(View.VISIBLE);
			if (mLiveDetailData != null
					&& mLiveDetailData.getRelatedVideos() != null
					&& mLiveDetailData.getRelatedVideos().size() > 0) {
				findViewById(R.id.hai_line).setVisibility(View.VISIBLE);
				related_grid.setVisibility(View.VISIBLE);
			}
			like_count_tv.setVisibility(View.VISIBLE);
			desc_line.setVisibility(View.VISIBLE);
			full_screen_bt.setVisibility(View.VISIBLE);
			like_finger2.setVisibility(View.GONE);
			full_screen_title_layout.setVisibility(View.GONE);
			kkd_logo.setAlpha(1f);
			LayoutParams paramsLogo = kkd_logo.getLayoutParams();
			paramsLogo.width = SystemUtils.dip2px(this, 57);
			paramsLogo.height = SystemUtils.dip2px(this, 17);
			kkd_logo.setLayoutParams(paramsLogo);
			android.widget.RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) surface_rl
					.getLayoutParams();
			params.width = SystemUtils.getScreenWidth(this);
			params.height = (int) (params.width * wPh);
			surface_rl.setLayoutParams(params);

			android.widget.RelativeLayout.LayoutParams params3 = (android.widget.RelativeLayout.LayoutParams) frameContainer
					.getLayoutParams();
			params3.width = SystemUtils.getScreenWidth(this);
			params3.height = (int) (params3.width * wPh);
			frameContainer.setLayoutParams(params3);

			LayoutParams parmFSL = full_screen_Layout.getLayoutParams();
			parmFSL.width = SystemUtils.dip2px(this, 18);
			parmFSL.height = SystemUtils.dip2px(this, 18);
			full_screen_Layout.setLayoutParams(parmFSL);
			LayoutParams parmBl = buttonLayout.getLayoutParams();
			parmBl.width = SystemUtils.dip2px(this, 32);
			parmBl.height = SystemUtils.dip2px(this, 36);
			buttonLayout.setLayoutParams(parmBl);

			android.widget.RelativeLayout.LayoutParams paramsPl = (android.widget.RelativeLayout.LayoutParams) progress_layout
					.getLayoutParams();
			paramsPl.height = SystemUtils.dip2px(this, 39);
			progress_layout.setLayoutParams(paramsPl);
			root_view.setFitsSystemWindows(true);
			root_view.setClipToPadding(false);
			mTintManager.setStatusBarTintResource(R.color.blue_5451b1);
		} else {
			title_rl.setVisibility(View.GONE);
			related_grid.setVisibility(View.GONE);
			findViewById(R.id.live_title).setVisibility(View.GONE);
			findViewById(R.id.like_frame).setVisibility(View.GONE);
			findViewById(R.id.hai_line).setVisibility(View.GONE);
			like_count_tv.setVisibility(View.GONE);
			desc_line.setVisibility(View.GONE);
			like_finger2.setVisibility(View.VISIBLE);
			full_screen_bt.setVisibility(View.GONE);
			full_screen_title_layout.setVisibility(View.VISIBLE);
			kkd_logo.setAlpha(0.3f);
			LayoutParams paramsLogo = kkd_logo.getLayoutParams();
			paramsLogo.width = LayoutParams.WRAP_CONTENT;
			paramsLogo.height = LayoutParams.WRAP_CONTENT;
			kkd_logo.setLayoutParams(paramsLogo);
			android.widget.RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) surface_rl
					.getLayoutParams();
			params.width = SystemUtils.getScreenRealWidth(this);
			params.height = SystemUtils.getScreenRealHeight(this);
			surface_rl.setLayoutParams(params);

			android.widget.RelativeLayout.LayoutParams params3 = (android.widget.RelativeLayout.LayoutParams) frameContainer
					.getLayoutParams();
			params3.width = SystemUtils.getScreenRealWidth(this);
			params3.height = SystemUtils.getScreenRealHeight(this);
			frameContainer.setLayoutParams(params3);
			LayoutParams parmFSL = full_screen_Layout.getLayoutParams();
			parmFSL.width = SystemUtils.dip2px(this, 22);
			parmFSL.height = SystemUtils.dip2px(this, 22);
			full_screen_Layout.setLayoutParams(parmFSL);
			LayoutParams parmBl = buttonLayout.getLayoutParams();
			parmBl.width = SystemUtils.dip2px(this, 36);
			parmBl.height = SystemUtils.dip2px(this, 44);
			buttonLayout.setLayoutParams(parmBl);
			root_view.setFitsSystemWindows(false);
			root_view.setClipToPadding(false);
			mTintManager.setStatusBarTintResource(R.color.black);
			android.widget.RelativeLayout.LayoutParams paramsPl = (android.widget.RelativeLayout.LayoutParams) progress_layout
					.getLayoutParams();
			paramsPl.height = SystemUtils.dip2px(this, 48);
			progress_layout.setLayoutParams(paramsPl);
		}
	}

	/**********
	 * 视频分享成功
	 **********/
	@Override
	public void videoShareSuccess() {
		String vid = mLiveHomeData.getVid();
		LogUtil.e("TAG", "视频分享成功了0.0" + vid);
		KkdHttpMagager.getInstance().getLiveShare(vid, String.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						LogUtil.e("TAG", "视频分享上传成功了");
					}

					@Override
					public void onFailure(int statusCode, String desc) {

					}
				});
	}
}
